var express = require('express');
var app = express();
var path = require("path")
var fs = require('fs');
var cookieParser = require('cookie-parser');
app.use(cookieParser('123456'));
var cors = require('cors');
app.use(cors());
app.use('/css', express.static('public/css'));
app.use('/fonts', express.static('public/fonts'));
app.use('/images', express.static('public/images'));
app.use('/js', express.static('public/js'));
app.use(express.json());
app.use(function (req, res, next) {
    var url = req.url;
    if (url == '/' && req.signedCookies.user) {
        res.redirect('/equipment');
        return;
    }
    // 判断不拦截的路由 出/login和/之外的都拦截
    if (url != '/index' && !req.signedCookies.user && url != '/register' && url != '/login') {
        res.clearCookie("user");
        res.redirect('/index');
        return;
    }
    //如果登录过，我们就执行下一个中间件
    console.log(req.signedCookies.user);
    next();
});

const { PromiseSocket } = require("promise-socket");
const net = require("net");
const netsocket = new net.Socket();
const socket = new PromiseSocket(netsocket);
const port = 28880;
const hostname = '123.56.66.9';
//const hostname = '127.0.0.1';
socket.setEncoding = 'UTF-8';



async function conn(json) {
    await socket.connect(port, hostname);
    await socket.write(JSON.stringify(json));
    socket.setTimeout(1000);
    let response = JSON.parse((await socket.readAll()).toString());
    console.log(response);
    return response;
}




//处理根目录的get请求
app.get('/index', function (req, res, next) {
    const options = {
        root: path.join(__dirname, ''),
        dotfiles: 'deny',
        headers: {
            'x-timestamp': Date.now(),
            'x-sent': true
        }
    }
    let fileName = 'public/index.html'
    res.sendFile(fileName, options, function (err) {
        if (err) {
            next(err)
        } else {
            console.log('Sent:', fileName)
        }
    })
    console.log('index page is required ');
});

app.get('/register', function (req, res, next) {
    const options = {
        root: path.join(__dirname, ''),
        dotfiles: 'deny',
        headers: {
            'x-timestamp': Date.now(),
            'x-sent': true
        }
    }
    let fileName = 'public/register.html'
    res.sendFile(fileName, options, function (err) {
        if (err) {
            next(err)
        } else {
            console.log('Sent:', fileName)
        }
    })
    console.log('register page is required ');
});

app.get('/login', async function (req, res) {
    res.send("不要直接访问我！");
});
// 处理/login的post请求
app.post('/login', async function (req, res) {
    console.log(req.body);
    let username = req.body.username;
    let pwd = req.body.password;
    let resp = await conn({ route: "webLogin", data: { action: 1, username: username, password: pwd } });
    if (resp.success == 1) {
        res.cookie("user", req.body.username, { maxAge: 60000000, httpOnly: false, signed: true });
        res.json({ success: 1 });
    } else {
        res.clearCookie('user');
        res.json({ success: 0 });
    }
});

app.get('/logout', function (req, res) { //删除Cookie  
    res.clearCookie('user');
    //回到/index路由
    res.redirect('/index');
});

app.get('/equipment', function (req, res, next) {
    const options = {
        root: path.join(__dirname, ''),
        dotfiles: 'deny',
        headers: {
            'x-timestamp': Date.now(),
            'x-sent': true
        }
    }
    let fileName = 'public/equipment.html'
    res.sendFile(fileName, options, function (err) {
        if (err) {
            next(err)
        } else {
            console.log('Sent:', fileName)
        }
    })
    console.log('equipment page is required ');
});

app.get('/userinfo', async function (req, res) {
    res.json({ username: req.signedCookies.user });
});

app.post('/devicecontrol', async function (req, res) {
    let info = await conn(req.body);
    res.json(info);
    console.log('devicecontrol is required ');
});

app.get('/deviceinfo', async function (req, res) {
    let info = await conn({ route: "showdeviceinfo", data: { username: req.signedCookies.user } });
    res.json(info);
    console.log('dinfo is required ');

});


// 监听3000端口
var server = app.listen(3000);
console.log('Start listening 3000');